package service

import (
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"golang.org/x/crypto/bcrypt"
	"shrimp-blog-server/app/dao"
	"shrimp-blog-server/app/model"
)

var (
	SuperAdmin = model.Role{
		Id:     1,
		Name:   "SuperAdmin",
		Status: 1,
	}
	Admin = model.Role{
		Id:     2,
		Name:   "admin",
		Status: 0,
	}
	User = model.Role{
		Id:     3,
		Name:   "user",
		Status: 1,
	}
	RoleMap = g.Map{
		"SuperAdmin": SuperAdmin,
		"admin":      Admin,
		"user":       User,
	}
)

func init() {
	g.Log().Info("-------------------------初始化角色--------------------------------")
	initRole()
	g.Log().Info("-------------------------初始化超级管理员信息--------------------------------")
	initSuperAdmin()
}

// initRole 初始化角色
func initRole() {
	roles, err := dao.Role.GetRolesByName(SuperAdmin.Name, Admin.Name, User.Name)
	if err != nil {
		panic(err)

	}
	if roles == nil {
		result, err := dao.Role.Insert(SuperAdmin, User, Admin)
		if err != nil {
			panic(err)

		}
		if result == 0 {
			panic("初始化角色失败,")
		}
	}
}
func initSuperAdmin() {
	password, err := bcrypt.GenerateFromPassword([]byte("Wangbiao970805"), bcrypt.DefaultCost)
	if err != nil {
		panic(gerror.Wrap(err, "初始化管理员信息加密密码失败"))
	}
	super := model.User{
		Id:       1,
		Username: "SuperAdmin",
		Password: string(password),
		Email:    "1061568698@qq.com",
		Avatar:   "http://gg.gg/xw6cs",
		Status:   1,
	}
	user, err := dao.User.GetUserById(super.Id)
	if err != nil {
		return
	}
	if user == nil {
		_, err2 := dao.User.Insert(super)
		if err2 != nil {
			panic(gerror.Wrap(err2, "初始化超级管理员用户失败"))
		}
	}
	var userRole model.UserRole
	dao.UserRole.DB().Model(dao.UserRole.Table).Where(g.Map{dao.UserRole.Columns.RoleId: SuperAdmin.Id, dao.UserRole.Columns.UserId: super.Id}).Scan(&userRole)
	if userRole.Id == 0 {
		_, err = dao.UserRole.Insert(model.UserRole{
			UserId: super.Id,
			RoleId: SuperAdmin.Id,
		})
		if err != nil {
			panic(gerror.Wrap(err, "初始化用户角色关联失败"))
		}
	}
}
